package com.yzg.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author misterWei
 * @create 2020年05月24号:13点43分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.CasAbASolve")
public class CasAbASolve {

    public static void main(String[] args) throws InterruptedException {
        int version = 0;
        AtomicStampedReference<String> a = new AtomicStampedReference("A",version);
        String perv = a.getReference();
        String next = "C";
        int stamp = a.getStamp();
        //ABA 问题发生
        options(a);
        Thread.sleep(1000L);
        /**
         *  stamp 当前版本号,  ++stamp 修改成功后修改版本号
         */
        a.compareAndSet(perv,next,stamp,++stamp);
        log.info(" 该值为: {}, 对应版本号为: {}",a.getReference(),stamp);
    }

    static void options( AtomicStampedReference<String> a){
        new Thread(()->{
            String perv = a.getReference();
            String next = "B";
            int stamp = a.getStamp();
            a.compareAndSet(perv,next,stamp,++stamp);
            log.info(" 该值为: {}, 对应版本号为: {}",a.getReference(),stamp);
        },"t1").start();

        new Thread(()->{
            String perv = a.getReference();
            String next = "A";
            int stamp = a.getStamp();
            a.compareAndSet(perv,next,stamp,++stamp);
            log.info(" 该值为: {}, 对应版本号为: {}",a.getReference(),stamp);
        },"t1").start();

    }
}
